#include "D5XAlgoDataSerilizer.h"
#include "../FilterSDK/ia.h"
#include <sstream>
#include <iomanip>

int CD5XAlgoDataSerilizer::SerilizeS1toS2Data(S1toS2Data& DatatoS2, unsigned char*& pData, int& len)
{
	len = sizeof(S1toS2Data);

	if (pData != NULL) {
		IA_FREE(pData);
	}
	IA_MALLOC(pData, unsigned char*, 0, len);

	memcpy(pData, &DatatoS2, len);

	IA_RETURN_OK
}

int CD5XAlgoDataSerilizer::ExtractS1toS2Data(const unsigned char* pData, int len, S1toS2Data* pDatatoS2)
{
	IA_ASSERT(len >= sizeof(S1toS2Data));
	IA_ASSERT(pData);

	memcpy(pDatatoS2, pData, len);

	IA_RETURN_OK;
}

int CD5XAlgoDataSerilizer::SerilizeFAIResult(D5XFAIResults result, unsigned char*& pData, int& len)
{
	len = sizeof(float) * FAI_SUB_CATEGORY_CNT;

	if (pData != NULL) {
		IA_FREE(pData);
	}
	IA_MALLOC(pData, unsigned char*, 0, len);

	memcpy(pData, result, sizeof(float) * FAI_SUB_CATEGORY_CNT);
	
	IA_RETURN_OK
}

int CD5XAlgoDataSerilizer::ExtractFAIResult(const unsigned char* pData, int len, D5XFAIResults pResult)
{
	IA_ASSERT(pData);
	IA_ASSERT(len >= sizeof(float) * FAI_SUB_CATEGORY_CNT);

	memcpy(pResult, pData, sizeof(float) * FAI_SUB_CATEGORY_CNT);

	IA_RETURN_OK
}

int CD5XAlgoDataSerilizer::FAIResult2List(int errCode, std::string timeStamp, D5XFAIResults results,
	std::vector < std::pair<std::string, std::string> >& itemList)
{
	// @See D5XUnit.h
	itemList.clear();

	itemList.emplace_back(std::make_pair("TimeStamp", timeStamp));
	itemList.emplace_back(std::make_pair("Error Code", std::to_string(errCode)));

	for (int i = 0; i < FAI_SUB_CATEGORY_CNT; i++) {
		// FAIResults is made of floats, which has the same memory layout with array
		std::ostringstream out;
		out << std::setprecision(3) << std::fixed << results[i];
		itemList.emplace_back(std::make_pair(D5XFAI::GetInstance().GetFAISubCatNames()[i], out.str()));
	}

	IA_RETURN_OK
}

